﻿using System.Reflection;

namespace CapHttp.Core.Extensions;

public static class TypeExtensions
{
    public static string GetEventName(this Type type)
    {
        if (type.IsGenericType)
        {
            var genericType = type.GetGenericTypeDefinition();
            var argumentNames = string.Join("-", type.GenericTypeArguments.Select(x => x.Name.PascalToDotCase()));
            return string.Concat(genericType.Name.PascalToDotCase(), ".", argumentNames);
        }
        
        var attribute = type.GetCustomAttribute<EventAttribute>();
        if (attribute == null || string.IsNullOrWhiteSpace(attribute.EventName))
        {
            var typeName = type.Name;
            if (typeName.EndsWith("Event") && typeName.Length > 5)
                typeName = typeName.Remove(typeName.Length - 5);
            return typeName.PascalToDotCase();
        }

        return attribute.EventName;
    }
}